<?php


namespace App\Common\Service;

use App\Common\Constants\ErrorCode;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Coroutine;
use Hyperf\Utils\Exception\ParallelExecutionException;
use Hyperf\Utils\Parallel;
use League\Flysystem\Filesystem;
use Exception;

class UploadFileService extends BaseService
{

    public function uploadImage(object $file)
    {
        try{
            $stream = fopen($file->getRealPath(), 'r+');
            $FileName = $file->getClientFilename(); //获取上传的文件名
            $Extension = substr($FileName, (strrpos($FileName, '.') + 1));//找到扩展名
            $Extension = strtolower($Extension);
            $FileName = date("YmdHis") . rand(100, 200) . time() . "." . $Extension;//产生新的文件名
            $this->filesystem->writeStream(
                env('OSS_DIR', 'ylxp-admin') . '/' . $FileName,
                $stream
            );
            @fclose($stream);
            $res = 'https://' . env('OSS_BUCKET', 'yiluxiaopao') . '.' . env('OSS_ENDPOINT', 'ylxp-oss.huadingyun.cn') . '/' . env('OSS_DIR', 'ylxp-admin') . '/' . $FileName;
//            $res = 'https://ylxp-oss.huadingyun.cn/ylxp-admin/' . $FileName;
        }catch (Exception $e){
            return ['code' => ErrorCode::SERVER_ERROR, 'msg' => $e->getMessage()];
        }
        return $res;

    }


    /**
     * 批量上传图片
     * @param array $path 图片地址数组
     * @return array
     */
    public function bulkUploadImg(array $path){
        $parallel = new Parallel(100);
        $count = count($path);
        if (!$count){
            return ['code' => 0, 'errorCode' => ErrorCode::SYSTEM_INVALID];
        }
        for ($i = 0; $i < $count; $i++) {
            $parallel->add(function () use($path, $i) {
                $fileContent = @file_get_contents($path[$i]);
                if ($fileContent){
                    $Extension = pathinfo($path[$i])['extension'] ?? '';
                    if ($Extension){
                        $config = [
                            "Content-Type" => 'image/jpeg'
                        ];
                        $time = microtime(true);
                        $filePath = env('OSS_AVATAR_DIR','face') . "/{$time}{$i}.{$Extension}";
                        $this->filesystem->write($filePath, $fileContent, $config);
                    }
                }
                return Coroutine::id();
            });
        }

        try{
            $results = $parallel->wait();
        } catch(ParallelExecutionException $e){
            $throw = $e->getThrowables();
            foreach ($throw as $v){
                return ['code' => 0, 'errorCode' => ErrorCode::SYSTEM_INVALID , 'msg' => $v->getMessage()];
            }
        }
        return ['code' => 1, 'msg' => 'success'];
    }


}
